﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Xml.Serialization;
using System.Xml;
using System.IO;
using System.Reflection;
using WindowsLive.Writer.Api;

namespace WindStyle.WindowsLiveWriter.Plugin.ExifInfo
{
    [Serializable]
    public class Option
    {
        /// <summary>
        /// Current Settings
        /// </summary>
        public static Settings CurrentSettings
        {
            get
            {
                if (field_settings == null)
                    field_settings = new Settings();
                return field_settings;
            }
        }
        private static Settings field_settings;

        private static IProperties field_properties;

        private const string SETTING_NAME = "ExifInfo-Settings";

        /// <summary>
        /// Serialize Settings to XML, then save it to IProperties
        /// </summary>
        public static void Save()
        {
            StringBuilder sb = new StringBuilder();
            XmlSerializer serializer = new XmlSerializer(typeof(Settings));
            using (XmlWriter writer = XmlWriter.Create(sb))
            {
                serializer.Serialize(writer, field_settings);
            }
            field_properties.SetString(SETTING_NAME, sb.ToString());
        }

        /// <summary>
        /// Load XML from IProperties, then Deserialze it to Settings
        /// </summary>
        /// <param name="properties">IProperties</param>
        public static void Load(IProperties properties)
        {
            field_properties = properties;
            string settings = field_properties.GetString(SETTING_NAME, null);
            if (settings == null)
            {
                field_settings = new Settings();
                field_settings.Reset();
            }
            else
            {
                XmlSerializer serializer = new XmlSerializer(typeof(Settings));
                field_settings = serializer.Deserialize(new MemoryStream(Encoding.GetEncoding("utf-16").GetBytes(settings))) as Settings;
            }
        }

        public static void Rollback()
        {
            if (field_properties != null)
                Load(field_properties);
        }
    }
}
